<template>
<a-tabs 
  v-model:activeKey="activeKey"
  size="small"
  hideAdd
  @edit="handleEdit"
  @change="handleChange"
  type="editable-card">
    <a-tab-pane v-for="(item,index) in tabList"
    :closable="item.closable" 
    :key="item.key">
    <template #tab>
      <a-dropdown :trigger="['contextmenu']">
        <span>{{ item.title }}</span>
        <template #overlay>
          <a-menu @click="handleMenuClick($event,item,index)">
            <a-menu-item v-for="i in contextmenuData" :key="i.key" :disabled="handleDisabled(i.key,item,index)">
              <MenuIcon v-if="i.icon" :icon="i.icon"/>
              {{i.title}}
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </template>
    </a-tab-pane>
  </a-tabs>
</template>
<script setup lang="ts">
import { ref,computed, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useTabStore } from '../store/modules/tab';
import MenuIcon from './MenuIcon.vue';
const route = useRoute()
const activeKey = ref(route.path)
const tabStore = useTabStore();
const contextmenuData = [{
  key: 'reload',
  title: '重新加载',
  icon: 'ReloadOutlined'
},{
  key: 'closeCurrent',
  title: '关闭当前',
  icon: 'CloseOutlined'
},{
  key: 'closeLeft',
  title: '关闭左侧',
  icon: 'VerticalLeftOutlined'
},{
  key: 'closeRight',
  title: '关闭右侧',
  icon: 'VerticalRightOutlined'
},{
  key: 'closeOther',
  title: '关闭其他',
  icon: 'MenuUnfoldOutlined'
},{
  key: 'closeAll',
  title: '关闭全部',
  icon: 'MinusOutlined'
}]
const tabList = computed(()=>{
  return tabStore.getTabs
})
watch(()=>route,()=>{
  activeKey.value = route.path
},{
  deep: true
})
const handleEdit = (targetKey: string,action: string)=>{
  if(action == 'remove') {
    tabStore.removeTab(targetKey)
  }
}
const handleChange = (key: string) => {
  tabStore.goToPage(key)
}
const handleDisabled = (action: string,data: any,index: number) =>{
  if(action == 'reload') {
    return !tabStore.isCurrent(data.key)
  }
  if(action == 'closeCurrent') {
    return !data.closable
  }
  if(action == 'closeLeft') {
    // 只有当前标签，才有关闭左侧
    if(!tabStore.isCurrent(data.key)) return true
    // 第一个没有关闭左侧
    if(index == 0) return true
  }
  if(action == 'closeRight') {
    // 只有当前标签，才有关闭右侧
    if(!tabStore.isCurrent(data.key)) return true
    // 最后一个没有关闭右侧
    if(index == tabList.value.length-1) return true
  }
  if(action == 'closeOther') {
    // 只有当前标签，才有关闭其他
    if(!tabStore.isCurrent(data.key)) return true
  }
  return false
}
const handleMenuClick = (e: any,data: any,index: number) =>{
  tabStore[e.key](data,index)
}
</script>
<style lang="less" scoped>

</style>